/* $Id: SchoolOlympServlet.java 117 2011-08-22 16:35:13Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;

import javax.servlet.ServletException;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import alt.djudge.frontend.server.datatypes.UserEntry;
import alt.djudge.frontend.server.datatypes.custom.SchoolOlympUserDetailsEntry;


public class SchoolOlympServlet extends AbstractServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String action = request.getParameter("action");
		if ("importUsers".equals(action))
		{
			String content = request.getParameter("file");
			String[] strings = content.split("\n");
			for (String str: strings)
				if (str.length() > 10)
    			{
    				String[] data = str.split(",");
    				for (int i = 0; i < data.length; i++)
    				{
    					data[i] = data[i].replace("\"\"", "\"");
    					data[i] = data[i].replace("\n", "");
    					response.getWriter().println(data[i]);
    				}
    				response.getWriter().println("****");
    				//if (true)
    					//continue;
    				//10        //0
    				//212       //1
    				//3                            //2
    				//Дудка Андрій Аркадійович     // 3
    				//м.Мукачево                   //4
    				//"Мукачівський навчально-виховний комплекс "Загальноосвітня школа І-ІІІ ступенів - дошкільний навчальний заклад "Гармонія" Мукачівської міської ради Закарпатської області"
    				String regionName = data[4];
    				String fullName = data[3];
    				String schoolName = data[5];
    				String formName = data[0];
    				String placeName = "n/a";
    				String teacherName = "n/a";
    				String loginName = data[1] + "_" + data[2];
    				UserEntry user = new UserEntry();
    				user.setUsername(loginName);
    				user.setRole("user");
    				user.generatePassword();
    				user.makePersistent();
    				SchoolOlympUserDetailsEntry detailsEntry = new SchoolOlympUserDetailsEntry();
    				detailsEntry.setUserId(user.getId());
    				detailsEntry.setFormNumber(Integer.parseInt(formName));
    				if (detailsEntry.getFormNumber().equals(8))
    					detailsEntry.setFormNumber(9);
    				detailsEntry.setLastName(fullName.split(" ")[0]);
    				detailsEntry.setFirstName(fullName.split(" ")[1]);
    				detailsEntry.setMiddleName(fullName.split(" ").length > 2 ? fullName.split(" ")[2] : "");
    				detailsEntry.setPrevPlace(placeName);
    				detailsEntry.setRegionName(regionName);
    				detailsEntry.setSchoolName(schoolName);
    				detailsEntry.setTeacherName(teacherName);
    				detailsEntry.makePersistent();
    				response.getWriter().println(user.getId());
    			}
		}
	}
}
